package user_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/blog_type"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/plugins/qq"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
)

func (UserApi) QqLoginView(c *gin.Context) {
	code := c.Query("code")
	if code == "" {
		http.FailWithMessage("没有code", c)
		return
	}
	qqInfo, err := qq.NewQQLogin(code)
	if err != nil {
		http.FailWithMessage(err.Error(), c)
		return
	}
	openid := qqInfo.OpenId
	user := new(models.UserModel)
	err = common.DB.Take(&user, "token = ?", openid).Error
	if err != nil {
		// 不存在,就注册
		user = &models.UserModel{
			NickName:   qqInfo.Nickname,
			UserName:   "",
			Password:   "",
			Avatar:     qqInfo.Avatar,
			Email:      "",
			Tel:        "",
			Addr:       "", // 根据 ip 计算
			Token:      openid,
			Ip:         c.ClientIP(),
			Role:       blog_type.PermissionUser,
			SignStatus: blog_type.LoginTypeQQ,
		}
		err = common.DB.Create(&user).Error
		if err != nil {
			common.Log.Error(err.Error())
			http.FailWithMessage("注册失败", c)
			return
		}
	}
	// 登录成功, 生成 token
	token, err := utils.GenUserToken(utils.JwtUser{
		NickName: user.NickName,
		Role:     int(user.Role),
		UserID:   user.ID,
	})
	if err != nil {
		common.Log.Error(err)
		http.FailWithMessage("登录失败，稍后重试", c)
		return
	}
	common.DB.Create(&models.LoginDataModel{
		UserID:    user.ID,
		IP:        c.ClientIP(),
		NickName:  user.NickName,
		Token:     token,
		Device:    "",
		Addr:      "内网",
		LoginType: blog_type.LoginTypeQQ,
	})
	http.IsOkWithData(token, c)
}
